package com.yang.service.adminimpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.yang.bean.*;
import com.yang.bean.common.BasePageInfo;
import com.yang.bean.common.BaseParam;
import com.yang.bean.common.CommonData;
import com.yang.bean.zdd.bo.CreateBo;
import com.yang.bean.zdd.vo.*;
import com.yang.mapper.*;
import com.yang.service.admin.GoodsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName GoodsServiceImpl
 * @Description TODO 商品模块service
 * @Author zhangdongdong
 * @Date 2022/9/7 20:37
 * @Version 1.0
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    MarketGoodsMapper goodsMapper;

    @Autowired
    MarketBrandMapper brandMapper;

    @Autowired
    MarketCategoryMapper categoryMapper;

    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;

    @Autowired
    MarketGoodsProductMapper productMapper;

    @Autowired
    MarketGoodsAttributeMapper attributeMapper;

    @Autowired
    MarketCommentMapper commentMapper;

    @Autowired
    MarketIssueMapper issueMapper;

    @Autowired
    MarketSearchHistoryMapper marketSearchHistoryMapper;

    @Autowired
    MarketFootPrintMapper footPrintMapper;

    /** 
     * @description: 回显/查询商品信息
     * @param: info goodsId goodsSn name
     * @return: com.yang.bean.common.CommonData<com.yang.bean.MarketGoods>
     * @author zhangdongdong
     * @date: 2022/9/8 16:45
     */ 
    @Override
    public CommonData<MarketGoods> list(BasePageInfo info, String goodsId, String goodsSn, String name) {
        if (info.getPage()!=null && info.getLimit()!=0){
            PageHelper.startPage(info.getPage(), info.getLimit());
        }
        MarketGoodsExample example = new MarketGoodsExample();
        if (!StringUtil.isEmpty(info.getSort()) || !StringUtils.isEmpty(info.getOrder())) {
            example.setOrderByClause(info.getSort() + " " + info.getOrder());
        }
        MarketGoodsExample.Criteria criteria = example.createCriteria();

        if (goodsId != null && !"".equals(goodsId)) {
            criteria.andIdEqualTo(Integer.parseInt(goodsId));
        }
        if (goodsSn != null && !"".equals(goodsSn)) {
            criteria.andGoodsSnEqualTo(goodsSn);
        }
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }

        List<MarketGoods> goodsList = goodsMapper.selectByExample(example);
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(goodsList);
        return CommonData.data(pageInfo);
    }
    
    /** 
     * @description: catAndBrand
     * @param: 
     * @return: com.yang.bean.zdd.vo.CatAndBrandVo
     * @author zhangdongdong
     * @date: 2022/9/8 17:32
     */ 
    @Override
    public CatAndBrandVo catAndBrand() {
        CatAndBrandVo catAndBrandVo = new CatAndBrandVo();

        //1:给brandList赋值
        List<BrandVo> brandList = new ArrayList();
        //查询market_brand表
        MarketBrandExample example = new MarketBrandExample();
        List<MarketBrand> marketBrands = brandMapper.selectByExample(example);
        for (MarketBrand brand : marketBrands) {
            BrandVo vo = new BrandVo();
            vo.setValue(brand.getId());
            vo.setLabel(brand.getName());
            brandList.add(vo);
        }
        catAndBrandVo.setBrandList(brandList);

        //2:给categoryList赋值
        List<CategoryVo> categoryList = new ArrayList<>();

        List<MarketCategory> marketCategories = categoryMapper.selectPidAll();

        for (MarketCategory category : marketCategories) {
            CategoryVo categoryVo = new CategoryVo();
            categoryVo.setValue(category.getId());
            categoryVo.setLabel(category.getName());
            MarketCategoryExample example2 = new MarketCategoryExample();
            MarketCategoryExample.Criteria criteria = example2.createCriteria();
            criteria.andPidEqualTo(category.getId());
            List<MarketCategory> children = categoryMapper.selectByExample(example2);
            List<ChildrenVo> list = new ArrayList<>();
            for (MarketCategory child : children) {
                ChildrenVo vo = new ChildrenVo();
                vo.setValue(child.getId());
                vo.setLabel(child.getName());
                list.add(vo);
            }
            categoryVo.setChildren(list);
            categoryList.add(categoryVo);
        }
        catAndBrandVo.setCategoryList(categoryList);

        return catAndBrandVo;
    }

    /** 
     * @description: 商品上架
     * @param: createBo
     * @return: void
     * @author zhangdongdong
     * @date: 2022/9/11 10:22
     */ 
    @Override
    public void create(CreateBo createBo) {
        MarketGoods goods = createBo.getGoods();
        List<MarketGoodsSpecification> specifications = createBo.getSpecifications();
        List<MarketGoodsProduct> products = createBo.getProducts();
        List<MarketGoodsAttribute> attributes = createBo.getAttributes();

        //1:插入goods
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = dateFormat.format(new Date());
        Date time = null;
        try {
            time = dateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //1.1:将keyword插入market_keyword表中
        MarketKeyWord keyWord = new MarketKeyWord();
        keyWord.setKeyword(goods.getKeywords());


        int minPrice = products.stream().mapToInt(u -> u.getPrice().intValue()).min().getAsInt();
        goods.setAddTime(time);
        goods.setUpdateTime(time);
        goods.setDeleted(false);
        goods.setRetailPrice(BigDecimal.valueOf(minPrice));
        goodsMapper.insertSelective(goods);

        Integer goodsId = goods.getId();

        //2:插入specifications
        for (MarketGoodsSpecification specification : specifications) {
            specification.setId(null);
            specification.setGoodsId(goodsId);
            specification.setAddTime(time);
            specification.setUpdateTime(time);
            specification.setDeleted(false);
            specificationMapper.insertSelective(specification);
        }

        //3:插入products
        for (MarketGoodsProduct product : products) {
            product.setId(null);
            product.setGoodsId(goodsId);
            product.setAddTime(time);
            product.setUpdateTime(time);
            product.setDeleted(false);
            productMapper.insertSelective(product);
        }

        //4:插入attributes
        for (MarketGoodsAttribute attribute : attributes) {
            attribute.setId(null);
            attribute.setGoodsId(goodsId);
            attribute.setAddTime(time);
            attribute.setUpdateTime(time);
            attribute.setDeleted(false);
            attributeMapper.insertSelective(attribute);
        }
    }

    @Override
    public DetailVo detail(Integer id) {

        //查询goods
        MarketGoods goods = goodsMapper.selectByPrimaryKey(id);

        //查询specification
        MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria specificationExampleCriteria = specificationExample.createCriteria();
        specificationExampleCriteria.andGoodsIdEqualTo(id);
        List<MarketGoodsSpecification> specifications = specificationMapper.selectByExample(specificationExample);

        //查询products
        MarketGoodsProductExample productExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria productExampleCriteria = productExample.createCriteria();
        productExampleCriteria.andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> products = productMapper.selectByExample(productExample);

        //查询attributes
        MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria attributeExampleCriteria = attributeExample.createCriteria();
        attributeExampleCriteria.andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> attributes = attributeMapper.selectByExample(attributeExample);

        //查询categoryIds
        Integer categoryId1 = goods.getCategoryId();
        MarketCategory category = categoryMapper.selectByPrimaryKey(categoryId1);
        Integer categoryPid2 = category.getPid();

        Integer[] categoryIds = {categoryId1, categoryPid2};

        DetailVo detailVo = new DetailVo();
        detailVo.setGoods(goods);
        detailVo.setAttributes(attributes);
        detailVo.setSpecifications(specifications);
        detailVo.setCategoryIds(categoryIds);
        detailVo.setProducts(products);

        return detailVo;
    }

    @Override
    public void update(CreateBo updateBo) {
        MarketGoods goods = updateBo.getGoods();
        List<MarketGoodsSpecification> specifications = updateBo.getSpecifications();
        List<MarketGoodsProduct> products = updateBo.getProducts();
        List<MarketGoodsAttribute> attributes = updateBo.getAttributes();

        //更新goods
        goodsMapper.updateByPrimaryKeySelective(goods);

        //更新specifications
        for (MarketGoodsSpecification specification : specifications) {
            specificationMapper.updateByPrimaryKeySelective(specification);
        }

        //更新products
        for (MarketGoodsProduct product : products) {
            productMapper.updateByPrimaryKeySelective(product);
        }

        //更新attributes
        for (MarketGoodsAttribute attribute : attributes) {
            attributeMapper.updateByPrimaryKeySelective(attribute);
        }
    }

    @Override
    public void delete(MarketGoods goods) {
        goodsMapper.deleteByPrimaryKey(goods.getId());
    }

    @Override
    public Long count() {
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        long num = goodsMapper.countByExample(goodsExample);
        return num;
    }

    @Override
    public GoodsCategoryVo category(Integer id) {
        //直接根据id查询出来的category;
        MarketCategory category1 = categoryMapper.selectByPrimaryKey(id);
        Integer pid = category1.getPid();

        //根据id对应的pid查询出来的category
        MarketCategory category2 = categoryMapper.selectByPrimaryKey(pid);


        MarketCategory currentCategory = null;
        MarketCategory parentCategory = null;
        List<MarketCategory> brotherCategory = null;

        //第一次点进
        if (pid == 0) {
            //parentCategory;
            //根据id查询parentCategory
            parentCategory = category1;

            //brotherCategory;
            //根据id->pid查询所有brotherCategory
            MarketCategoryExample categoryExample = new MarketCategoryExample();
            categoryExample.createCriteria().andPidEqualTo(id);
            brotherCategory = categoryMapper.selectByExample(categoryExample);

            //currentCategory;
            //传进来的id作为pid
            currentCategory = brotherCategory.get(0);
        } else {
            //currentCategory;
            //根据id查询currentCategory
            currentCategory = category1;

            //parentCategory;
            //根据pid查询parentCategory
            parentCategory = category2;

            //brotherCategory;
            //根据pid查询所有brotherCategory
            MarketCategoryExample categoryExample = new MarketCategoryExample();
            categoryExample.createCriteria().andPidEqualTo(pid);
            brotherCategory = categoryMapper.selectByExample(categoryExample);
        }

        GoodsCategoryVo data = new GoodsCategoryVo();
        data.setCurrentCategory(currentCategory);
        data.setParentCategory(parentCategory);
        data.setBrotherCategory(brotherCategory);

        return data;
    }

    /**
     * @description: 搜索商品/按照商品类目显示商品
     * @param: baseParam
     * categoryId
     * keyword
     * userId
     * @return: com.yang.bean.zdd.vo.ListInWxVo
     * @author zhangdongdong
     * @date: 2022/9/11 16:40
     */
    @Override
    public ListInWxVo listInWx(BaseParam baseParam, Integer categoryId, Integer brandId, String keyword, Integer userId) {

        //list
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        if (baseParam.getOrder() != null && baseParam.getSort() != null) {
            goodsExample.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        }

        MarketGoodsExample.Criteria criteria = goodsExample.createCriteria();
        if (keyword != null && !"".equals(keyword)) {
            criteria.andNameLike("%" + keyword + "%");
        }
        if (categoryId != null && categoryId != 0) {
            criteria.andCategoryIdEqualTo(categoryId);
        }
        if (brandId != null) {
            criteria.andBrandIdEqualTo(brandId);
        }

        List<MarketGoods> list = goodsMapper.selectByExample(goodsExample);
        List<MarketGoods> collect = list.stream().limit(baseParam.getLimit()).collect(Collectors.toList());

        //filterCategoryList
        MarketCategoryExample categoryExample = new MarketCategoryExample();
        List<MarketCategory> filterCategoryList = categoryMapper.selectByExample(categoryExample);

        //page
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(collect);

        //TODO 根据搜索的keyword进行插入search,传入用户的id;
        //搜索完成插入数据（前提：已经登录）
        if (keyword != null && !"".equals(keyword)) {
            MarketSearchHistory marketSearchHistory = new MarketSearchHistory();
            marketSearchHistory.setAddTime(new Date());
            marketSearchHistory.setFrom("wx");
            marketSearchHistory.setKeyword(keyword);
            marketSearchHistory.setUserId(userId);
            marketSearchHistoryMapper.insertSelective(marketSearchHistory);
        }

        return ListInWxVo.data(pageInfo, filterCategoryList);
    }

    /**
     * @description: 显示商品详细信息 TODO:用户未登录时无法将当前浏览过的商品添加到footprint表中
     * @param: id
     * @return: com.yang.bean.zdd.vo.GoodsDetailVo
     * @author zhangdongdong
     * @date: 2022/9/11 10:08
     */
    @Override
    public GoodsDetailVo detailInWx(Integer id, Integer userId) {
        //attribution
        MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
        attributeExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> attribution = attributeMapper.selectByExample(attributeExample);

        //info
        MarketGoods info = goodsMapper.selectByPrimaryKey(id);
        info.setAddTime(new Date());

        //brand
        MarketBrand brand = brandMapper.selectByPrimaryKey(info.getBrandId());

        //comment
        CommentVo comment = new CommentVo();
        MarketCommentExample commentExample = new MarketCommentExample();
        commentExample.createCriteria().andValueIdEqualTo(id);
        List<MarketComment> commentList = commentMapper.selectByExample(commentExample);
        List<MarketComment> collect = commentList.stream().limit(2).collect(Collectors.toList());
        comment.setData(collect);
        comment.setCount(commentList.size());

        //groupon

        //issue
        MarketIssueExample issueExample = new MarketIssueExample();
        List<MarketIssue> issue = issueMapper.selectByExample(issueExample);

        //productList
        MarketGoodsProductExample productExample = new MarketGoodsProductExample();
        productExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> productList = productMapper.selectByExample(productExample);

        //share

        //shareImage

        //specificationList
        List<GoodsSpecificationVo> specificationList = new ArrayList<>();

        List<MarketGoodsSpecification> groupList = specificationMapper.selectGroupBySpecification(id);
        for (MarketGoodsSpecification group : groupList) {
            GoodsSpecificationVo vo = new GoodsSpecificationVo();
            vo.setName(group.getSpecification());
            //根据vo的specification查询
            MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
            specificationExample.createCriteria().andSpecificationEqualTo(group.getSpecification()).andGoodsIdEqualTo(id);
            List<MarketGoodsSpecification> valueList = specificationMapper.selectByExample(specificationExample);
            vo.setValueList(valueList);
            specificationList.add(vo);
        }

        //userHasCollect

        GoodsDetailVo data = new GoodsDetailVo();
        data.setAttribute(attribution);
        data.setBrand(brand);
        data.setComment(comment);
        data.setGroupon(new ArrayList<String>());
        data.setInfo(info);
        data.setIssue(issue);
        data.setProductList(productList);
        data.setShare(true);
        data.setShareImage("");
        data.setSpecificationList(specificationList);
        data.setUserHasCollect(0);

        //todo：将当前浏览的商品添加到足迹
        MarketFootPrint marketFootPrint = new MarketFootPrint();
        marketFootPrint.setUserId(userId);
        marketFootPrint.setGoodsId(info.getId());
        marketFootPrint.setAddTime(new Date());
        marketFootPrint.setUpdateTime(new Date());
        marketFootPrint.setDeleted(false);
        footPrintMapper.insertSelective(marketFootPrint);
        goodsMapper.updateByPrimaryKeySelective(info);

        return data;
    }

    @Override
    public CommonData related(Integer id) {

//        PageHelper.startPage(1, 6);

        //根据id查出对应商品，再根据其category_id查询相关产品
        MarketGoods goods = goodsMapper.selectByPrimaryKey(id);

        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andCategoryIdEqualTo(goods.getCategoryId());
        List<MarketGoods> goodsList = goodsMapper.selectByExample(goodsExample);

        Stream<MarketGoods> stream = goodsList.stream().limit(6);
        List<MarketGoods> collect = stream.collect(Collectors.toList());

        PageInfo<MarketGoods> pageInfo = new PageInfo<>(collect);
        pageInfo.setPageNum(1);
        pageInfo.setPageSize(6);
        pageInfo.setPages((int) (pageInfo.getTotal() / 6));

        return CommonData.data(pageInfo);
    }



}
